<!--
 * @Description: 绑定门店表单弹窗
-->
<template>
  <a-drawer title="绑定门店" :open="visible" @close="onClose">
    <template #closeIcon>
      <div class="express-bar"></div>
      <div class="express-btn">
        <CloseCircleOutlined :size="32" @click="onClose" />
      </div>
    </template>
    <a-card size="small" :bordered="false">
      <a-form style="margin: 20px 0">
        <a-row :gutter="[8, 10]">
          <a-col :span="4">
            <a-form-item label="门店" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.store_name" placeholder="门店" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-button-group>
              <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
                <template #icon>
                  <SearchOutlined />
                </template>
                查询
              </a-button>
              <a-button @click="resetQuery" v-privilege="'goods:query'">
                <template #icon>
                  <ReloadOutlined />
                </template>
                重置
              </a-button>
            </a-button-group>
          </a-col>
        </a-row>
      </a-form>
      <div class="table-wrapper">
        <a-table size="small" :dataSource="tableData" :columns="columns" row-key="id" bordered :scroll="{ x: 'max-content' }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, onSelect: onSelect, onSelectAll: onSelectAll, getCheckboxProps: getCheckboxProps, preserveSelectedRowKeys: true }">
          <template #bodyCell="{ text, record, column }">
            <template v-if="column.dataIndex === 'salesman'">
              <span>{{ text && text.length > 0 ? text.map((e) => e.rename).join(',') : '' }}</span>
            </template>
            <template v-if="column.dataIndex === 'dealer'">
              <span>{{ text && text.length > 0 ? text.map((e) => e.name).join(',') : '' }}</span>
            </template>
          </template>
        </a-table>
      </div>
      <div class="smart-query-table-page query-table-page">
        <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
      </div>
    </a-card>
    <template #footer>
      <div class="smart-table-operate-block">
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </div>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import { lineApi } from '@/api/business/data/line-api'
import { useQuery } from '@/hooks/web/use-query-hook'
// ----------------------------- 计算表格高度 -----------------------------
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reload-list'])

const selectedRowKeyList = ref([])
const selectedRows = ref([])

function onSelectChange(selectedRowKeys, selectedRows) {
  selectedRowKeyList.value = selectedRowKeys
  selectedRows.value = selectedRows
}
function onSelect(record, selected, selectedRows) {
  if (!Array.isArray(selectedRows.value)) {
    selectedRows.value = []
  }
  if (selected) {
    selectedRows.value.push(record)
  }

  if (!selected) {
    const delIndex = selectedRows.value.findIndex((val) => {
      return val.id === record.id
    })
    selectedRows.value.splice(delIndex, 1)
  }
}

function onSelectAll(selected, selectedRows, changeRows) {
  if (!Array.isArray(selectedRows.value)) {
    selectedRows.value = []
  }
  if (selected) {
    selectedRows.value = selectedRows.value.concat(changeRows)
  }
  if (!selected) {
    let selectedRows = JSON.parse(JSON.stringify(selectedRows.value))
    const delIndex = []
    selectedRows.forEach((item, index) => {
      changeRows.forEach((val, itemIndex) => {
        if (item.id === val.id) {
          delIndex.push(index)
        }
      })
    })
    delIndex.forEach((item) => {
      delete selectedRows[item]
    })
    selectedRows = selectedRows.filter((item) => {
      return item !== undefined
    })
    selectedRows.value = selectedRows
  }
}

const columns = computed(() => [
  {
    title: '门店',
    dataIndex: 'store_name',
    width: 200
  },
  {
    title: '联系人',
    dataIndex: 'contacts',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'phone'
  },
  {
    title: '所属片区',
    dataIndex: ['region', 'name'],
    width: 100
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '录入时间',
    dataIndex: 'create_time'
  }
])
// ---------------------------- 查询数据表单和方法 ----------------------------
const query = ref([])
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, setQuery } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      store_name: queryForm.value.store_name
    }
    const res = await lineApi.lineStoreList(data)

    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {},
  queryFormOp: {}
})
function getCheckboxProps(record) {
  return {
    disabled: record.is_bind === 1 && !query.value.find(({ id }) => id === record.id)
  }
}
// ---------------------------- 展示抽屉 ----------------------------
// 是否展示抽屉
const visible = ref(false)
const lineId = ref('')
function showDrawer(rowData, Id) {
  visible.value = true
  query.value = rowData
  query.value.forEach((item) => {
    if (!selectedRowKeyList.value.includes(item.id)) {
      selectedRowKeyList.value.push(item.id)
    }
  })
  lineId.value = Id
  queryData()
}

function onClose() {
  resetQuery(false)
  query.value = []
  selectedRowKeyList.value = []
  visible.value = false
}

async function onSubmit() {
  loadingStore.show()
  const params = {
    id: lineId.value,
    store_id: selectedRowKeyList.value.join(',')
  }
  try {
    await lineApi.lineBindStore(params)
    message.success('操作成功')
    onClose()
    emit('reload-list')
  } catch (error) {
    message.error(error.msg)
    errorSentry.captureError(error)
  } finally {
    loadingStore.hide()
  }
}

defineExpose({
  showDrawer
})
</script>
<style scoped lang="less">
.icon-content {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  padding-top: 8px;
  padding-bottom: 8px;
  cursor: pointer;
  line-height: 22px;
  border: 0;
  border-bottom: 1px solid;
  border-color: #ccc;
}
.icon-content:hover {
  background-color: #f5f7fa;
}
</style>
